package com.anxin.act.process.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anxin.act.task.service.ActTaskService;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 自由流相关Service
 * @author: liuxiangyu
 * @date: 2020/4/26 15:27
 */
@Service
public class ActFreeFlowService {


    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 自由流启动时审批人设置
     * @param procInsId
     * @param nextApply
     */
    public void startApproval(String procInsId, JSONArray nextApply){
        //将用户id转换为登录名
        JSONArray nextUserIdApply = new JSONArray();
        for (int i = 0; i < nextApply.size(); i++) {
            JSONObject nextUserIdObject = nextApply.getJSONObject(i);
            nextUserIdApply.add(nextUserIdObject.getString("user"));
        }

        JSONArray userNameArray = UserUtils.idToLoginName(nextUserIdApply);
        TaskEntity currentTask = ActTaskUtils.getCurrentTask(procInsId);
        String nextApplyUserName = userNameArray.get(0).toString();
        // 设置下一审批人
        ActTaskUtils.claimTask(currentTask.getId(), nextApplyUserName);
        taskService.setOwner(currentTask.getId(), nextApplyUserName);
        taskService.setAssignee(currentTask.getId(), nextApplyUserName);

        //选择的全部审批人
        runtimeService.setVariable(procInsId, "freeFlowAssigneesAll", userNameArray.toJSONString());
        userNameArray.remove(0);
        //剩余未审的审批人
        runtimeService.setVariable(procInsId, "freeFlowAssignees", userNameArray.toJSONString());

    }

    /**
     * 获取自由流接下来的审批人
     * @param taskVo
     * @return
     */
    public void getNextApproval(TaskVo taskVo){
        taskVo.setNextApprovalArray(new JSONArray());
        if ("act_free_flow_approval".equals(taskVo.getProcessDefKey())){
            Object freeFlowAssignees = runtimeService.getVariable(taskVo.getActId(), "freeFlowAssignees");
            if (freeFlowAssignees != null){
                JSONArray freeFlowAssigneesArray = JSONObject.parseArray(freeFlowAssignees.toString());
                for (int i = 0; i < freeFlowAssigneesArray.size(); i++) {
                    String nextApproval = freeFlowAssigneesArray.getString(i);
                    SysUser sysUser = UserUtils.getUserByUserName(nextApproval);
                    if (sysUser != null){
                        taskVo.getNextApprovalArray().add(sysUser.getNickName());
                    }
                }
            }
        }
    }
}
